package com.cntv.viewmodeldemo.fragment

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import androidx.activity.viewModels
import androidx.annotation.Nullable
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.observe
import com.cntv.viewmodeldemo.R
import com.cntv.viewmodeldemo.savestate.KTXSaveStateViewModel
import kotlinx.android.synthetic.main.activity_users.*
//const val name ="编译时常量"
/**
 * activity与fragment   和    fragment与fragment通信
 */
class UsersActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_users)

        supportFragmentManager.beginTransaction().replace(R.id.fragment_container_1, TopFragment()).commit()
        supportFragmentManager.beginTransaction().replace(R.id.fragment_container_2, BottomFragment()).commit()
//        val mModel = ViewModelProvider(this).get(UserModel::class.java)
        val mModel: UserModel by viewModels()
        main_set_button.setOnClickListener {
            mModel.setUser("jack", "188*****888", "这段数据是从Activity中Post出来的")
        }

//        mModel.getUser()?.observe(this, Observer {
//            //当数据有变化并且页面处于活跃状态 update ui.
//            textView.text = UserModel.getFormatContent(it.name,
//            it.phone,
//            it.address) })
        /**
         *这里 observe 和上面不同。这里是livedata-ktx扩展提供的。对比上面，下面就是使用kotlin语言特性的写法
         */
        mModel.getUser()?.observe(this){user->
            textView.text = UserModel.getFormatContent(user.name,
                user.phone,
                user.address)
        }

    }
}